import { Entity } from '../systems/EntitySystem.js';
import { RenderSystem } from '../systems/RenderSystem.js';
import { GameConfig, MissileType } from '../config/GameConfig.js';
import { Poolable } from '../systems/PerformanceOptimizationSystem.js';

// 导弹飞行阶段
export enum FlightPhase {
    LAUNCH = 'launch',
    CRUISE = 'cruise',
    DIVE = 'dive',
    EXPLODED = 'exploded'
}

// 轨迹点
export interface TrajectoryPoint {
    x: number;
    y: number;
    time: number;
}

export class Missile implements Entity, Poolable {
    public id: string;
    public x: number;
    public y: number;
    public width: number = 8;
    public height: number = 25;
    public active: boolean = true;
    
    private missileType: MissileType;
    private config: any;
    private health: number;
    private maxHealth: number;
    private velocity: { x: number; y: number } = { x: 0, y: 0 };
    private currentPhase: FlightPhase = FlightPhase.LAUNCH;
    private flightTime: number = 0;
    private totalFlightTime: number;
    private trajectory: TrajectoryPoint[] = [];
    private targetX: number;
    private targetY: number;
    private trailPoints: { x: number; y: number; alpha: number }[] = [];
    private rotation: number = 0;

    constructor(id: string, missileType: MissileType, startX: number, startY: number, targetX: number, targetY: number) {
        this.id = id;
        this.missileType = missileType;
        this.config = GameConfig.MISSILES[missileType];
        this.health = this.config.health;
        this.maxHealth = this.config.health;
        this.totalFlightTime = this.config.flightTime;
        this.x = startX;
        this.y = startY;
        this.targetX = targetX;
        this.targetY = targetY;
        
        // 🎯 调试日志：显示导弹目标坐标
        console.log(`🚀 导弹 ${this.id} (${missileType}) 创建: 起点(${startX.toFixed(0)}, ${startY.toFixed(0)}) → 目标(${targetX.toFixed(0)}, ${targetY.toFixed(0)})`);
        
        this.calculateTrajectory();
        this.setInitialVelocity();
    }

    private calculateTrajectory(): void {
        const distance = Math.sqrt(Math.pow(this.targetX - this.x, 2) + Math.pow(this.targetY - this.y, 2));
        const segments = Math.floor(this.totalFlightTime / 1000); // 每秒一个轨迹点
        
        for (let i = 0; i <= segments; i++) {
            const progress = i / segments;
            const time = progress * this.totalFlightTime;
            
            let x, y;
            
            if (this.missileType === 'FATTAH_2') {
                // 超音速导弹：低空巡航
                x = this.x + (this.targetX - this.x) * progress;
                y = this.y + Math.sin(progress * Math.PI) * 30; // 轻微的弧线
            } else if (this.missileType === 'SHAHED_136') {
                // 无人机：锯齿形飞行
                x = this.x + (this.targetX - this.x) * progress;
                y = this.y + Math.sin(progress * Math.PI * 4) * 20 + (this.targetY - this.y) * progress * 0.3;
            } else {
                // 弹道导弹：抛物线轨迹
                x = this.x + (this.targetX - this.x) * progress;
                const height = Math.sin(progress * Math.PI) * (distance * 0.3); // 抛物线高度
                y = this.y + (this.targetY - this.y) * progress - height;
            }
            
            this.trajectory.push({ x, y, time });
        }
    }

    private setInitialVelocity(): void {
        // 使用配置文件中的真实速度值
        const speed = this.getCurrentSpeed();
        const dx = this.targetX - this.x;
        const dy = this.targetY - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        // 归一化方向向量并应用速度
        this.velocity.x = (dx / distance) * speed;
        this.velocity.y = (dy / distance) * speed;
    }
    
    private getCurrentSpeed(): number {
        switch (this.currentPhase) {
            case FlightPhase.LAUNCH:
                return this.missileType === 'FATTAH_2' ? this.config.cruiseSpeed : 
                       this.missileType === 'SHAHED_136' ? this.config.cruiseSpeed :
                       this.config.horizontalSpeed || this.config.cruiseSpeed || 100;
            case FlightPhase.CRUISE:
                return this.missileType === 'FATTAH_2' ? this.config.cruiseSpeed :
                       this.missileType === 'SHAHED_136' ? this.config.cruiseSpeed :
                       this.config.horizontalSpeed || this.config.cruiseSpeed || 80;
            case FlightPhase.DIVE:
                return this.missileType === 'FATTAH_2' ? this.config.attackSpeed :
                       this.missileType === 'SHAHED_136' ? this.config.attackSpeed :
                       this.config.diveSpeed || this.config.attackSpeed || 150;
            default:
                return 60;
        }
    }

    update(deltaTime: number): void {
        if (!this.active) return;

        this.flightTime += deltaTime;
        
        // 更新飞行阶段
        this.updateFlightPhase();
        
        // 更新位置
        this.updatePosition(deltaTime);
        
        // 更新尾迹
        this.updateTrail();
        
        // 检查是否到达目标
        if (this.flightTime >= this.totalFlightTime) {
            this.explode();
        }
    }

    private updateFlightPhase(): void {
        const progress = this.flightTime / this.totalFlightTime;
        
        if (this.missileType === 'FATTAH_2') {
            if (progress < 0.1) this.currentPhase = FlightPhase.LAUNCH;
            else if (progress < 0.8) this.currentPhase = FlightPhase.CRUISE;
            else this.currentPhase = FlightPhase.DIVE;
        } else if (this.missileType === 'SHAHED_136') {
            if (progress < 0.15) this.currentPhase = FlightPhase.LAUNCH;
            else if (progress < 0.9) this.currentPhase = FlightPhase.CRUISE;
            else this.currentPhase = FlightPhase.DIVE;
        } else {
            if (progress < 0.2) this.currentPhase = FlightPhase.LAUNCH;
            else if (progress < 0.7) this.currentPhase = FlightPhase.CRUISE;
            else this.currentPhase = FlightPhase.DIVE;
        }
    }

    private updatePosition(deltaTime: number): void {
        // 基于物理速度的直接位置更新
        this.x += this.velocity.x * (deltaTime / 1000);
        this.y += this.velocity.y * (deltaTime / 1000);
        
        // 根据飞行阶段调整速度
        const newSpeed = this.getCurrentSpeed();
        const currentSpeed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
        
        if (currentSpeed > 0) {
            const speedRatio = newSpeed / currentSpeed;
            this.velocity.x *= speedRatio;
            this.velocity.y *= speedRatio;
        }
        
        // 检查边界
        if (this.x < 0 || this.x > GameConfig.CANVAS_WIDTH || 
            this.y < 0 || this.y > GameConfig.CANVAS_HEIGHT) {
            this.explode();
        }
        
        // 检查是否击中建筑物
        this.checkBuildingCollision();
        
        // 检查是否接近目标
        const distanceToTarget = Math.sqrt(
            Math.pow(this.targetX - this.x, 2) + 
            Math.pow(this.targetY - this.y, 2)
        );
        
        if (distanceToTarget < 20) {
            this.explode();
        }
    }

    private checkBuildingCollision(): void {
        // 通过全局引用检查建筑物碰撞
        const gameEngine = (globalThis as any).gameEngine;
        if (gameEngine && gameEngine.entitySystem) {
            // 🔍 详细的导弹位置日志（提高频率到10%）
            if (Math.random() < 0.1) { // 10%概率输出，便于调试
                console.log(`🔍 导弹 ${this.id} 当前位置: (${this.x.toFixed(0)}, ${this.y.toFixed(0)})`);
                console.log(`   目标位置: (${this.targetX.toFixed(0)}, ${this.targetY.toFixed(0)})`);
                console.log(`   飞行阶段: ${this.currentPhase}`);
                console.log(`   飞行时间: ${(this.flightTime/1000).toFixed(1)}s / ${(this.totalFlightTime/1000).toFixed(1)}s`);
                
                // 计算到目标的距离
                const distanceToTarget = Math.sqrt(
                    Math.pow(this.targetX - this.x, 2) + 
                    Math.pow(this.targetY - this.y, 2)
                );
                console.log(`   距离目标: ${distanceToTarget.toFixed(0)}px`);
                
                // 列出所有建筑物位置
                const buildings = gameEngine.entitySystem.getBuildings();
                console.log(`   可用建筑物: ${buildings.length}个`);
                buildings.forEach((building: any) => {
                    const distance = Math.sqrt(
                        Math.pow(building.x - this.x, 2) + 
                        Math.pow(building.y - this.y, 2)
                    );
                    console.log(`     ${building.getBuildingName()} @ (${building.x}, ${building.y}) 距离: ${distance.toFixed(0)}px`);
                });
            }
            
            const hitBuilding = gameEngine.entitySystem.checkMissileHitBuildings(this.x, this.y, this.config.damage);
            if (hitBuilding) {
                console.log(`🎯🎯🎯 导弹 ${this.id} 击中 ${hitBuilding.getBuildingName()}！位置: (${this.x.toFixed(0)}, ${this.y.toFixed(0)})`);
                this.explode();
            }
        }
    }

    private updateTrail(): void {
        // 添加新的尾迹点
        this.trailPoints.unshift({ x: this.x, y: this.y, alpha: 1.0 });
        
        // 更新尾迹透明度并移除旧点
        for (let i = this.trailPoints.length - 1; i >= 0; i--) {
            this.trailPoints[i].alpha -= 0.05;
            if (this.trailPoints[i].alpha <= 0 || i > 20) {
                this.trailPoints.splice(i, 1);
            }
        }
    }

    private explode(): void {
        this.currentPhase = FlightPhase.EXPLODED;
        this.active = false;
        console.log(`💥 导弹 ${this.id} 爆炸于 (${this.x.toFixed(0)}, ${this.y.toFixed(0)})`);
    }

    render(renderSystem: RenderSystem): void {
        if (!this.active) return;

        // 渲染尾迹
        this.renderTrail(renderSystem);
        
        // 渲染导弹主体
        this.renderMissileBody(renderSystem);
        
        // 渲染推进尾焰
        this.renderThrustFlame(renderSystem);
        
        // 渲染健康条（调试用）
        if (GameConfig.DEBUG.ENABLED) {
            this.renderHealthBar(renderSystem);
        }
    }

    private renderTrail(renderSystem: RenderSystem): void {
        for (let i = 0; i < this.trailPoints.length - 1; i++) {
            const current = this.trailPoints[i];
            const next = this.trailPoints[i + 1];
            
            const color = this.getTrailColor();
            const alpha = current.alpha * 0.5;
            
            renderSystem.renderLine(
                current.x, current.y,
                next.x, next.y,
                `rgba(${color}, ${alpha})`,
                2
            );
        }
    }

    private renderMissileBody(renderSystem: RenderSystem): void {
        const color = this.getMissileColor();
        const icon = this.getMissileIcon();
        
        // 计算导弹旋转角度
        const angle = Math.atan2(this.velocity.y, this.velocity.x);
        
        // 尝试使用SVG渲染
        const svgRendered = (renderSystem as any).renderMissileWithSVG?.(
            this.missileType, 
            this.x, this.y, 
            this.width, this.height, 
            angle,
            color,
            icon
        );
        
        // 如果SVG渲染失败，使用备用渲染方案
        if (!svgRendered) {
            // 备用方案：使用几何形状和emoji
            const ctx = (renderSystem as any).ctx;
            ctx.save();
            ctx.translate(this.x, this.y);
            ctx.rotate(angle);
            
            // 渲染导弹主体（火箭形状）
            ctx.fillStyle = color;
            ctx.fillRect(-this.width/2, -this.height/2, this.width, this.height);
            
            // 渲染尖头
            ctx.fillStyle = '#ff4444';
            ctx.beginPath();
            ctx.moveTo(this.width/2, 0);
            ctx.lineTo(this.width/2 - 8, -3);
            ctx.lineTo(this.width/2 - 8, 3);
            ctx.closePath();
            ctx.fill();
            
            ctx.restore();
            
            // 渲染图标
            renderSystem.renderText(icon, this.x - 8, this.y - 20, 'white', 'bold 12px Arial');
        }
    }

    private renderThrustFlame(renderSystem: RenderSystem): void {
        if (this.currentPhase === FlightPhase.LAUNCH || this.currentPhase === FlightPhase.DIVE) {
            const flameLength = this.currentPhase === FlightPhase.LAUNCH ? 15 : 8;
            const flameX = this.x - this.velocity.x * 0.1;
            const flameY = this.y - this.velocity.y * 0.1;
            
            // 渲染推进火焰
            renderSystem.renderLine(
                this.x, this.y,
                flameX, flameY,
                this.getFlameColor(),
                3
            );
        }
    }

    private renderHealthBar(renderSystem: RenderSystem): void {
        const barWidth = this.width + 10;
        const barHeight = 3;
        const healthPercent = this.health / this.maxHealth;
        
        // 背景
        renderSystem.renderEntity(
            this.x, this.y - this.height/2 - 8,
            barWidth, barHeight,
            'rgba(0, 0, 0, 0.5)'
        );
        
        // 健康条
        renderSystem.renderEntity(
            this.x - barWidth/2 + (barWidth * healthPercent)/2,
            this.y - this.height/2 - 8,
            barWidth * healthPercent, barHeight,
            healthPercent > 0.5 ? '#28a745' : healthPercent > 0.2 ? '#ffc107' : '#dc3545'
        );
    }

    private getMissileColor(): string {
        switch (this.missileType) {
            case 'FATTAH_2':
                return '#FFB627'; // 超音速导弹 - 金色
            case 'SHAHED_136':
                return '#7B2D26'; // 无人机 - 深红色
            default:
                return GameConfig.COLORS.IRAN_PRIMARY; // 其他导弹 - 标准红色
        }
    }

    private getTrailColor(): string {
        switch (this.currentPhase) {
            case FlightPhase.LAUNCH:
                return '255, 255, 255'; // 白色
            case FlightPhase.CRUISE:
                return '255, 165, 0'; // 橙色
            case FlightPhase.DIVE:
                return '255, 69, 0'; // 红橙色
            default:
                return '255, 255, 255';
        }
    }

    private getFlameColor(): string {
        switch (this.currentPhase) {
            case FlightPhase.LAUNCH:
                return '#87CEEB'; // 蓝白色推进火焰
            case FlightPhase.DIVE:
                return '#FF4500'; // 红橙色俯冲火焰
            default:
                return '#FFA500';
        }
    }

    private getMissileIcon(): string {
        switch (this.missileType) {
            case 'FATEH_110':
                return '🚀';
            case 'SHAHAB_3':
                return '🎯';
            case 'FATTAH_2':
                return '⚡';
            case 'SHAHED_136':
                return '🛩️';
            case 'QIAM_1':
                return '📍';
            case 'ZELZAL_2':
                return '💥';
            default:
                return '🚀';
        }
    }

    // 公共接口
    public takeDamage(damage: number): boolean {
        this.health -= damage;
        if (this.health <= 0) {
            this.explode();
            return true; // 导弹被摧毁
        }
        return false; // 导弹未被摧毁
    }

    public getHealth(): number {
        return this.health;
    }

    public getMaxHealth(): number {
        return this.maxHealth;
    }

    public getMissileType(): MissileType {
        return this.missileType;
    }

    public getCurrentPhase(): FlightPhase {
        return this.currentPhase;
    }

    public getFlightProgress(): number {
        return this.flightTime / this.totalFlightTime;
    }

    public getPosition(): { x: number; y: number } {
        return { x: this.x, y: this.y };
    }

    public getVelocity(): { x: number; y: number } {
        return { ...this.velocity };
    }

    public getDamage(): number {
        return this.config.damage;
    }

    public destroy(): void {
        this.active = false;
        this.trailPoints = [];
        this.trajectory = [];
    }

    // Poolable interface implementation
    public reset(): void {
        this.active = true;
        this.health = this.maxHealth;
        this.flightTime = 0;
        this.currentPhase = FlightPhase.LAUNCH;
        this.trailPoints = [];
        this.trajectory = [];
        this.velocity = { x: 0, y: 0 };
        this.rotation = 0;
    }

    public isActive(): boolean {
        return this.active;
    }

    public setActive(active: boolean): void {
        this.active = active;
    }
}
